﻿using System;
using System.Diagnostics;
using System.Speech.Synthesis;
using System.Windows.Forms;

namespace Devv.SpeechWaver
{
	public partial class MainForm : Form
	{
		#region Properties

		private SpeechSynthesizer S = new SpeechSynthesizer();

		#endregion

		#region Main methods

		public MainForm()
		{
			InitializeComponent();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			cboSpeed.SelectedIndex = 2;
		}

		private void linkDevv_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			Process.Start("http://speechwaver.devv.com/");
		}

		#endregion

		#region Options and Save

		private void imgFolder_Click(object sender, EventArgs e)
		{
			if (openFile.ShowDialog() == DialogResult.OK)
			{
				txtPath.Text = openFile.FileName;
			}
		}

		private void butSave_Click(object sender, EventArgs e)
		{
			Application.DoEvents();

			if (String.IsNullOrWhiteSpace(txtPhrase.Text))
			{
				return;
			}

			try
			{
				if (S.State != SynthesizerState.Ready)
				{
					Pause();
				}
			}
			catch
			{
				
			}

			Speak();
		}

		private void Speak()
		{
			S = new SpeechSynthesizer();

			Int32 rate = 5;

			switch (cboSpeed.SelectedIndex)
			{
				case 0:
					rate = 3; break;
				case 1:
					rate = 1; break;
				case 2:
					rate = -2; break;
				case 3:
					rate = -3; break;
				case 4:
					rate = -5; break;
			}

			S.Rate = rate;
			S.Volume = 100;
			S.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Adult);

			if (String.IsNullOrWhiteSpace(txtPath.Text))
			{
				S.SetOutputToDefaultAudioDevice();
			}
			else
			{
				txtPath.Enabled = false;
				S.SetOutputToWaveFile(txtPath.Text);
				S.SpeakCompleted += SpeakCompleted;
			}

			S.SpeakAsync(txtPhrase.Text);
		}

		private void SpeakCompleted(Object sender, SpeakCompletedEventArgs e)
		{
			if (S != null)
			{
				S.Dispose();

				Process.Start(txtPath.Text); 
				txtPath.Enabled = true;
			}

		}

		private void Pause()
		{
			if (S == null)
			{
				return;
			}

			S.Pause();
			S.Dispose();
		}

		#endregion
	}
}
